package com.test.latitudex;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.test.latitudex.utilities.LocationBroadcastReceiver;
import com.test.latitudex.utilities.RegistrationManager;

public class LoginActivity extends Activity {

	@SuppressWarnings("unused")
	private static final String LOG_TAG = "LoginActivity";
	private static final int accountActivityResultCode = 100;
	private static final int applicationActivityResultCode = 300;

	int minTime, minDist;

	static String interval = null, duration = null, id = null;
	static Button loginButton;
	static Button createButton;
	static EditText userNameEdit;
	static EditText passwordEdit;
	static TextView forgotText;
	static String userId;
	static LocationBroadcastReceiver brc;
	static Context ctx;
	static String lastUpdate = null;
	static boolean serviceStarted = false;
	static RegistrationManager rManager;
	static ProgressDialog dialog;
	Intent intent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ctx = this;
		SharedPreferences settings = ctx.getSharedPreferences(RegistrationManager.PREFS_NAME, 0);

		if(!this.getIntent().getBooleanExtra(RegistrationManager.FROM_LOGOUT, false)){
			if (!(settings.getString("email", "").equals("") || settings.getString("password", "").equals("") || settings
					.getString("id", "").equals(""))) {
				intent = new Intent(ctx, MainActivity.class);
				intent.putExtra(RegistrationManager.IS_LOGGED_IN, true);
				startActivityForResult(intent, applicationActivityResultCode);
				finish();
			}
		}else{
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("id", "");
			editor.commit();
		}
		
		setContentView(R.layout.login_screen_layout);
		rManager = RegistrationManager.getEntity();
		rManager.setAppContext(ctx);
		loginButton = (Button) findViewById(R.id.loginButton);
		createButton = (Button) findViewById(R.id.createButton);
		userNameEdit = (EditText) findViewById(R.id.userName);
		passwordEdit = (EditText) findViewById(R.id.password);
		forgotText = (TextView) findViewById(R.id.forgotPassText);
		loginButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				login();
			}
		});
		createButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				intent = new Intent(ctx, CreateAccountActivity.class);
				startActivityForResult(intent, accountActivityResultCode);
			}

		});

		forgotText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// intent = new Intent(ctx, ForgotPasswordActivity.class);
				// startActivityForResult(intent, forgotPasswordActivityResultCode);
			}

		});
		if (!(settings.getString("email", "").equals("") || settings.getString("password", "").equals(""))) {
			userNameEdit.setText(settings.getString("email", ""));
			passwordEdit.setText(settings.getString("password", ""));

		}
	}

	void login() {

		runOnUiThread(new Runnable() {
			public void run() {
				dialog = ProgressDialog.show(LoginActivity.this, "", "Logging in... Please wait!", true);

			}
		});

		new Thread(new Runnable() {
			public void run() {
				try {
					if (rManager.login(userNameEdit.getText().toString(), passwordEdit.getText().toString())) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								dialog.setMessage("Downloading data... Please wait!");
							}
						});
						RegistrationManager.getEntity().downloadData();
						RegistrationManager.getEntity().downloadInvitations();
						dialog.dismiss();
						intent = new Intent(ctx, MainActivity.class);
						startActivityForResult(intent, applicationActivityResultCode);
						finish();
					} else {
						dialog.dismiss();
					}
				} catch (final Exception e) {
					dialog.dismiss();
					runOnUiThread(new Thread(new Runnable() {
						public void run() {
							if (e.getMessage().contains("401")) {
								Toast.makeText(ctx, "Unauthorized. Username or password is incorrect.",
										Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(ctx, "Login unsuccesful. Please check network connection.",
										Toast.LENGTH_LONG).show();
							}
						}
					}));
				}
			}
		}).start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
